package lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname PrintByReentrantLock
 * @Description TODO
 * @Date 2020/2/16 11:29 下午
 * @Created by gule
 */
public class PrintByReentrantLock {
    private static Integer count = 0;
    private static boolean flag = true;
    private static Integer defaultValue = 200;
    private static ReentrantLock lock = new ReentrantLock(false);
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(()->{

                while (count < defaultValue) {
                    lock.lock();
                    if (flag) {
                        System.out.println("偶数 num is " + count);
                        count++;
                        flag = false;
                    }
                    else{
                        //这个时候会出现cpu空转的问题，应该调用线程进去sleep
                    }
                    lock.unlock();
                }

        });
        executorService.execute(()->{
                while (count < defaultValue) {
                    lock.lock();
                    if (!flag) {
                        System.out.println("奇数 num is " + count);
                        count++;
                        flag = true;
                    }else{
                        //这个时候会出现cpu空转的问题，应该调用线程进去sleep
                    }
                    lock.unlock();
                }
        });
    }
}
